<?php

namespace app\model;

use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;

class RoomSettlementDetail extends Model
{
    protected $table = 'room_settlement_details';
    
    protected $fillable = [
        'settlement_id',
        'room_id',
        'user_id',
        'username',
        'final_score',
        'is_winner',
        'is_room_owner',
        'joined_at',
        'left_at',
        'settlement_strategy'
    ];

    protected $casts = [
        'settlement_id' => 'integer',
        'room_id' => 'integer',
        'user_id' => 'integer',
        'final_score' => 'integer',
        'is_winner' => 'boolean',
        'is_room_owner' => 'boolean',
        'settlement_strategy' => 'array',
        'joined_at' => 'datetime',
        'left_at' => 'datetime',
        'created_at' => 'datetime',
        'updated_at' => 'datetime'
    ];

    /**
     * 关联结算记录
     */
    public function settlement()
    {
        return $this->belongsTo(RoomSettlement::class, 'settlement_id');
    }

    /**
     * 关联房间
     */
    public function room()
    {
        return $this->belongsTo(Room::class, 'room_id');
    }

    /**
     * 关联用户
     */
    public function user()
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    /**
     * 创建结算详情记录
     */
    public static function createSettlementDetails($settlementId, $roomId, $playersData, $settlementStrategies = [])
    {
        $details = [];
        
        foreach ($playersData as $player) {
            $userId = $player['user_id'];
            $userStrategy = $settlementStrategies[$userId] ?? null;
            
            $details[] = [
                'settlement_id' => $settlementId,
                'room_id' => $roomId,
                'user_id' => $userId,
                'username' => $player['username'],
                'final_score' => $player['final_score'],
                'is_winner' => $player['is_winner'],
                'is_room_owner' => $player['is_room_owner'],
                'joined_at' => $player['joined_at'],
                'left_at' => $player['left_at'],
                'settlement_strategy' => $userStrategy,
                'created_at' => Carbon::now(),
                'updated_at' => Carbon::now()
            ];
        }
        
        return self::insert($details);
    }

    /**
     * 保存用户结算策略
     */
    public static function saveUserSettlementStrategy($userId, $roomId, $strategy)
    {
        // 检查房间状态
        $room = \app\model\Room::find($roomId);
        if (!$room || $room->status === 'finished') {
            throw new \Exception('房间不存在或已结算，无法保存结算策略');
        }
        
        // 检查用户在房间中的状态
        $roomUser = \app\model\RoomUser::where('room_id', $roomId)
            ->where('user_id', $userId)
            ->first();
            
        if (!$roomUser) {
            throw new \Exception('用户不在该房间中');
        }
        
        if ($roomUser->status === \app\model\RoomUser::STATUS_FINISHED) {
            throw new \Exception('您在该房间的结算已完成，无法保存结算策略');
        }
        
        // 检查是否已经生成过策略
        $existingDetail = self::where('user_id', $userId)
            ->where('room_id', $roomId)
            ->whereNotNull('settlement_strategy')
            ->first();
            
        if ($existingDetail) {
            // 更新现有记录
            $existingDetail->update(['settlement_strategy' => $strategy]);
            return $existingDetail;
        }
        
        // 创建新记录
        return self::create([
            'settlement_id' => 0, // 临时记录，后续会更新
            'room_id' => $roomId,
            'user_id' => $userId,
            'username' => \app\model\User::find($userId)->username ?? '未知用户',
            'final_score' => 0, // 临时值，后续会更新
            'is_winner' => false, // 临时值，后续会更新
            'is_room_owner' => false, // 临时值，后续会更新
            'settlement_strategy' => $strategy,
            'joined_at' => null,
            'left_at' => null
        ]);
    }

    /**
     * 检查用户是否已生成结算策略
     */
    public static function hasUserGeneratedStrategy($userId, $roomId)
    {
        return self::where('user_id', $userId)
            ->where('room_id', $roomId)
            ->whereNotNull('settlement_strategy')
            ->exists();
    }

    /**
     * 获取房间内已生成策略的用户数量
     */
    public static function getRoomGeneratedStrategyCount($roomId)
    {
        return self::where('room_id', $roomId)
            ->whereNotNull('settlement_strategy')
            ->distinct('user_id')
            ->count('user_id');
    }

    /**
     * 获取房间内所有用户数量
     */
    public static function getRoomTotalUserCount($roomId)
    {
        return \app\model\RoomUser::where('room_id', $roomId)
            ->whereIn('status', [\app\model\RoomUser::STATUS_ACTIVE, \app\model\RoomUser::STATUS_LEFT])
            ->count();
    }

    /**
     * 检查是否所有用户都已生成策略
     */
    public static function allUsersGeneratedStrategy($roomId)
    {
        $generatedCount = self::getRoomGeneratedStrategyCount($roomId);
        $totalCount = self::getRoomTotalUserCount($roomId);
        
        return $generatedCount >= $totalCount;
    }

    /**
     * 获取用户的结算历史
     */
    public static function getUserSettlementHistory($userId, $page = 1, $pageSize = 20)
    {
        return self::where('user_id', $userId)
            ->with(['settlement', 'room'])
            ->orderBy('created_at', 'desc')
            ->paginate($pageSize, ['*'], 'page', $page);
    }

    /**
     * 获取房间的结算详情
     */
    public static function getRoomSettlementDetails($settlementId)
    {
        return self::where('settlement_id', $settlementId)
            ->with(['user'])
            ->get();
    }

    /**
     * 获取用户的统计信息
     */
    public static function getUserStats($userId)
    {
        $totalGames = self::where('user_id', $userId)->count();
        $totalWins = self::where('user_id', $userId)->where('is_winner', true)->count();
        $totalLosses = self::where('user_id', $userId)->where('is_winner', false)->count();
        $winRate = $totalGames > 0 ? round(($totalWins / $totalGames) * 100, 2) : 0;
        
        $totalScore = self::where('user_id', $userId)->sum('final_score');
        $maxScore = self::where('user_id', $userId)->max('final_score');
        $minScore = self::where('user_id', $userId)->min('final_score');
        
        return [
            'total_games' => $totalGames,
            'total_wins' => $totalWins,
            'total_losses' => $totalLosses,
            'win_rate' => $winRate,
            'total_score' => $totalScore,
            'max_score' => $maxScore,
            'min_score' => $minScore
        ];
    }
}
